package cn.cutie.clot.fs;

import lombok.SneakyThrows;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/7/16 09:57
 * @Version: 0.0.1
 */
@Component
public class HttpSyncer {

    public static final String X_FILE_NAME = "X-FileName";
    public static final String X_ORIGIN_FILE_NAME = "X-Origin-FileName";

    public String sync(File file, String backupUrl, String originalFilename){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add(X_FILE_NAME, file.getName());
        headers.add(X_ORIGIN_FILE_NAME, originalFilename);

        MultipartBodyBuilder builder = new MultipartBodyBuilder();
        builder.part("file", new FileSystemResource(file));
        HttpEntity<MultiValueMap<String, HttpEntity<?>>> httpEntity = new HttpEntity<>(builder.build(), headers);
//        String result = restTemplate.postForObject(backupUrl, httpEntity, String.class);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(backupUrl, httpEntity, String.class);
        String result = responseEntity.getBody();
        System.out.println("sync result: " + result);
        return result;
    }
}
